package cn.view;

import cn.comon.CSVUtil;
import cn.comon.VerticalTextCellRenderer;
import cn.dao.GoodsDao;
import cn.entity.Goods;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class GoodsManageView extends JInternalFrame {
    JTable detail;
    DefaultTableModel model;
    JPanel Jbutton;

    public GoodsManageView() {
        super("商品管理页面", false, true, false, true);
        initializeComponents();
        this.setSize(700, 500);
        this.setVisible(true);
    }

    private void initializeComponents() {
        // 设置布局管理器
        getContentPane().setLayout(new BorderLayout());
        // 初始化数据和按钮
        getDetailData();
        setButton();
    }

    private void getDetailData() {
        GoodsDao dao = new GoodsDao();
        List<Object[]> ls = dao.selectAll();
        String[] title = { "商品编号", "商品名称", "商品单价", "客户编号", "商品简介", "备注" };
        model = new DefaultTableModel(ls.toArray(new Object[][]{}), title);
        detail = new JTable(model);
        detail.setDefaultEditor(Object.class, null);
        detail.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        // 设置表格列宽
        setColumnWidths(detail, new int[]{100, 100,80, 100, 140, 140});
        // 设置表格行高
        detail.setRowHeight(15);
        // 设置自定义渲染器
        for (int i = 0; i < detail.getColumnCount(); i++) {
            detail.getColumnModel().getColumn(i).setCellRenderer(new VerticalTextCellRenderer());
        }

        JScrollPane scrollPane = new JScrollPane(detail, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }

    private void setColumnWidths(JTable table, int[] widths) {
        for (int i = 0; i < widths.length; i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
        }
    }

    public void refreshGoodsData(){
        GoodsDao dao = new GoodsDao();
        List<Object[]> ls = dao.selectAll();
        model.setRowCount(0);
        for (Object[] row : ls) {
            model.addRow(row);
        }
    }

    private JPanel createGoodsFormPanel(JTextField[] fields) {
        for (int i = 0; i < fields.length; i++) {
            fields[i] = new JTextField(10);
        }

        JPanel panel = new JPanel(new GridLayout(6, 2));
        panel.add(new JLabel("商品编号:"));
        panel.add(fields[0]);
        panel.add(new JLabel("商品名称:"));
        panel.add(fields[1]);
        panel.add(new JLabel("商品单价:"));
        panel.add(fields[2]);
        panel.add(new JLabel("客户编号:"));
        panel.add(fields[3]);
        panel.add(new JLabel("商品简介:"));
        panel.add(fields[4]);
        panel.add(new JLabel("备注:"));
        panel.add(fields[5]);

        return panel;
    }

    private Goods getGoodsFromFields(JTextField[] fields) {
        Goods good = new Goods();
        good.setGid(fields[0].getText()); // 商品编号
        good.setGname(fields[1].getText()); // 商品名称

        // 对价格字段进行空值检查
        String priceText = fields[2].getText().trim();
        if (!priceText.isEmpty()) {
            good.setPrice(Float.parseFloat(priceText)); // 商品单价，注意转换为Float类型
        }
            /*else {}
            为了不让else空体，这里添加了一个注释
            如果价格字段为空，你可以选择不设置价格，或者设置一个默认值
            这里选择不设置，即保留Goods对象中的默认值（可能为null）
            */

        good.setCid(fields[3].getText()); // 客户编号
        good.setIntroduction(fields[4].getText()); // 商品简介
        good.setNotes(fields[5].getText()); // 备注
        return good;
    }

    private List<Goods> convertToGoodsList(List<Object[]> data) {
        List<Goods> goodsList = new ArrayList<>();
        for (Object[] row : data) {
            Goods good = new Goods();
            good.setGid((String) row[0]); // 商品编号
            good.setGname((String) row[1]); // 商品名称
            good.setPrice(((Number) row[2]).floatValue()); // 商品单价，假设数据库查询结果为Number类型
            good.setCid((String) row[3]); // 客户编号
            good.setIntroduction((String) row[4]); // 商品简介
            good.setNotes((String) row[5]); // 备注
            goodsList.add(good);
        }
        return goodsList;
    }

    private void showAddGoodsDialog() {
        JTextField[] fields = new JTextField[6];
        JPanel panel = createGoodsFormPanel(fields); // 假设这个方法已修改为创建商品表单

        int result = JOptionPane.showConfirmDialog(null, panel, "添加商品", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            Goods good = getGoodsFromFields(fields);

            GoodsDao dao = new GoodsDao();
            List<Goods> goodsList = new ArrayList<>();
            goodsList.add(good);
            dao.addGoods(goodsList);

            // 更新表格视图
            model.addRow(new Object[]{
                    good.getGid(),
                    good.getGname(),
                    good.getPrice(),
                    good.getCid(),
                    good.getIntroduction(),
                    good.getNotes()
            });
            refreshGoodsData();
        }
    }

    private void showEditGoodsDialog(int selectedRow) {
        JTextField[] fields = new JTextField[6];
        JPanel panel = createGoodsFormPanel(fields);

        // 填充现有商品数据
        fields[0].setText((String) model.getValueAt(selectedRow, 0)); // Gid
        fields[1].setText((String) model.getValueAt(selectedRow, 1)); // GName
        fields[2].setText(model.getValueAt(selectedRow, 2).toString()); // Price, 注意转换为String
        fields[3].setText((String) model.getValueAt(selectedRow, 3)); // Cid
        fields[4].setText((String) model.getValueAt(selectedRow, 4)); // Introduction
        fields[5].setText((String) model.getValueAt(selectedRow, 5)); // Notes

        int result = JOptionPane.showConfirmDialog(null, panel, "修改商品", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String originalGid = (String) model.getValueAt(selectedRow, 0);
            Goods good = getGoodsFromFields(fields);

            GoodsDao dao = new GoodsDao();
            dao.updateGoods(good, originalGid);

            // 更新表格视图
            model.setValueAt(good.getGid(), selectedRow, 0);
            model.setValueAt(good.getGname(), selectedRow, 1);
            model.setValueAt(good.getPrice(), selectedRow, 2);
            model.setValueAt(good.getCid(), selectedRow, 3);
            model.setValueAt(good.getIntroduction(), selectedRow, 4);
            model.setValueAt(good.getNotes(), selectedRow, 5);
        }
    }

    private void showQueryGoodsDialog() {
        JTextField[] fields = new JTextField[6]; // 商品信息有6个字段
        JPanel panel = createGoodsFormPanel(fields);

        int result = JOptionPane.showConfirmDialog(null, panel, "查询商品", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            Goods criteria = getGoodsFromFields(fields);

            GoodsDao dao = new GoodsDao(); // 商品数据库操作类
            List<Goods> goodsList = dao.queryGoods(criteria); // 查询商品信息

            if (goodsList.isEmpty()) {
                JOptionPane.showMessageDialog(null, "没有符合的商品信息");
            } else {
                // 清空现有表格数据
                model.setRowCount(0);
                // 添加查询结果到表格
                for (Goods good : goodsList) {
                    model.addRow(new Object[]{
                            good.getGid(), // 商品编号
                            good.getGname(), // 商品名称
                            good.getPrice(), // 商品单价
                            good.getCid(), // 客户编号
                            good.getIntroduction(), // 商品简介
                            good.getNotes() // 备注
                    });
                }
            }
        }
    }

    private void showExportGoodsDialog() {
        String[] options = {"导出所有商品数据", "导出筛选后的商品数据", "导出除筛选外的商品数据"};
        int choice = JOptionPane.showOptionDialog(
                null,
                "请选择导出选项",
                "导出商品数据",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.INFORMATION_MESSAGE,
                null,
                options,
                options[0]
        );

        // 如果用户选择关闭对话框或点击取消按钮，直接返回
        if (choice == JOptionPane.CLOSED_OPTION) {
            return;
        }

        List<Goods> goodsToExport = new ArrayList<>();

        if (choice == 0) { // 导出所有商品数据
            GoodsDao dao = new GoodsDao();
            List<Object[]> allGoodsData = dao.selectAll();
            goodsToExport = convertToGoodsList(allGoodsData);
        } else {
            JTextField[] fields = new JTextField[6]; // 商品信息有6个字段
            JPanel panel = createGoodsFormPanel(fields);

            int result = JOptionPane.showConfirmDialog(null, panel, "筛选商品", JOptionPane.OK_CANCEL_OPTION);
            // 如果用户选择关闭对话框或点击取消按钮，直接返回
            if (result == JOptionPane.CLOSED_OPTION || result == JOptionPane.CANCEL_OPTION) {
                return;
            }

            Goods criteria = getGoodsFromFields(fields);
            GoodsDao dao = new GoodsDao();
            List<Goods> filteredGoods = dao.queryGoods(criteria);

            if (choice == 1) { // 导出筛选后的商品数据
                goodsToExport = filteredGoods;
            } else if (choice == 2) { // 导出除筛选外的商品数据
                List<Object[]> allGoodsData = dao.selectAll();
                List<Goods> allGoods = convertToGoodsList(allGoodsData);
                allGoods.removeAll(filteredGoods);
                goodsToExport = allGoods;
            }
        }

        if (!goodsToExport.isEmpty()) {
            exportGoodsToCSV(goodsToExport); // 假设此方法用于导出商品数据到CSV
        } else {
            JOptionPane.showMessageDialog(null, "没有符合条件的商品数据可导出");
        }
    }


    private void exportGoodsToCSV(List<Goods> goods) {
        String[] headers = {"商品编号", "商品名称", "商品单价", "客户编号", "商品简介", "备注"};
        List<Object[]> data = new ArrayList<>();

        for (Goods good : goods) {
            data.add(new Object[]{
                    good.getGid(),
                    good.getGname(),
                    good.getPrice(),
                    good.getCid(),
                    good.getIntroduction(),
                    good.getNotes()
            });
        }

        File csvFile = CSVUtil.createCSVFile(headers, data, "output/path", "商品数据");
        if (csvFile != null) {
            JOptionPane.showMessageDialog(null, "商品数据已成功导出到: " + csvFile.getAbsolutePath());
        } else {
            JOptionPane.showMessageDialog(null, "导出商品数据失败");
        }
    }

    private void setButton() {
        Jbutton = new JPanel();
        Jbutton.setLayout(new FlowLayout());

        JButton addButton = new JButton("添加商品");
        addButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showAddGoodsDialog();
            }
        });

        JButton editButton = new JButton("修改商品");
        editButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int selectedRow = detail.getSelectedRow();
                if (selectedRow != -1) {
                    showEditGoodsDialog(selectedRow);
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要修改的商品");
                }
            }
        });

        JButton delButton = new JButton("删除商品");
        delButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int selectedRow = detail.getSelectedRow();
                if (selectedRow != -1) {
                    String gid = (String) model.getValueAt(selectedRow, 0);
                    GoodsDao dao = new GoodsDao();
                    dao.deleteGood(gid);
                    model.removeRow(selectedRow);
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要删除的商品");
                }
            }
        });

        JButton queryButton = new JButton("查询商品");
        queryButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showQueryGoodsDialog();
            }
        });

        JButton exportButton = new JButton("导出商品数据");
        exportButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showExportGoodsDialog();
            }
        });

        Jbutton.add(addButton);
        Jbutton.add(editButton);
        Jbutton.add(delButton);
        Jbutton.add(queryButton);
        Jbutton.add(exportButton);

        getContentPane().add(Jbutton, BorderLayout.SOUTH);
    }
}
